#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include"LockGuard.hpp"
#define NUM 4

using namespace std;
//全局定义一把锁，就可以不用初始化和销毁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;


class threadData
{
public:
    // threadData(int number,pthread_mutex_t *lock)
    // {
    //     threadname="thread-"+to_string(number);
    //     _lock=lock;
    // }
    threadData(int number)
    {
        threadname="thread-"+to_string(number);
        
    }

public:
    string threadname;
    // pthread_mutex_t *_lock;
};

int tickets = 30; // 假设x张票
void *getTicket(void*args)
{
    threadData*td=static_cast<threadData*>(args);
    const char*name=td->threadname.c_str();
    while(true)
    {
        {
        LockGuard LockGuard(&lock);
        if(tickets>0)
        {
            usleep(1000);
            printf("who:%s, get a tickets: %d\n",name,tickets);
            tickets--;
            // pthread_mutex_unlock(td->_lock);
            pthread_mutex_unlock(&lock);

        }
        else
        {
            // pthread_mutex_unlock(td->_lock);
            pthread_mutex_unlock(&lock);
            break;
        }
        }
        usleep(13);
    }
    return nullptr;
}
// void *getTicket(void*args)
// {
//     threadData*td=static_cast<threadData*>(args);
//     const char*name=td->threadname.c_str();
//     while(true)
//     {
//         // pthread_mutex_lock(td->_lock);
//         pthread_mutex_lock(&lock);
//         if(tickets>0)
//         {
//             usleep(1000);
//             printf("who:%s, get a tickets: %d\n",name,tickets);
//             tickets--;
//             // pthread_mutex_unlock(td->_lock);
//             pthread_mutex_unlock(&lock);

//         }
//         else
//         {
//             // pthread_mutex_unlock(td->_lock);
//             pthread_mutex_unlock(&lock);
//             break;
//         }
//         usleep(13);
//     }
//     return nullptr;
// }


int main()
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock,nullptr);
    vector<pthread_t> tids;
    vector<threadData *> thread_datas;
    for(int i =1;i<=NUM;i++)
    {
        pthread_t tid;
        // threadData* td = new threadData(i,&lock);
        threadData* td = new threadData(i);
        thread_datas.push_back(td);
        pthread_create(&tid,nullptr,getTicket,thread_datas[i-1]);
        tids.push_back(tid);
    }
    for (auto thread : tids)
    {
        pthread_join(thread, nullptr);
    }

    for (auto td : thread_datas)
    {
        delete td;
    }
    // pthread_mutex_destroy(&lock);
    return 0;
}